import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

/// 文档标签显示组件
class DocumentTagsWidget extends StatelessWidget {
  final Map<String, dynamic> document;
  final bool showTitle;
  final int maxTags;
  final bool showMoreButton;
  final double fontSize;
  final double spacing;
  final EdgeInsets padding;
  final Color tagBackgroundColor;
  final Color? tagTextColor;
  final VoidCallback? onTagPressed;

  const DocumentTagsWidget({
    Key? key,
    required this.document,
    this.showTitle = true,
    this.maxTags = 4, // 减少默认显示数量
    this.showMoreButton = true,
    this.fontSize = 12.0,
    this.spacing = 4.0,
    this.padding = const EdgeInsets.all(8.0),
    this.tagBackgroundColor = const Color(0xFFE3F2FD),
    this.tagTextColor,
    this.onTagPressed,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final tags = _getDocumentTags();
    
    if (tags.isEmpty) {
      return SizedBox.shrink();
    }

    return Padding(
      padding: padding,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          if (showTitle)
            Padding(
              padding: EdgeInsets.only(bottom: 8.0),
              child: Text(
                '标签',
                style: TextStyle(
                  fontSize: fontSize + 2,
                  fontWeight: FontWeight.w500,
                  color: Colors.grey[700],
                ),
              ),
            ),
          _buildTagChips(context, tags),
        ],
      ),
    );
  }

  List<String> _getDocumentTags() {
    try {
      final tags = document['tags'];
      if (tags is List) {
        return tags.cast<String>().where((tag) => tag.trim().isNotEmpty).toList();
      } else if (tags is String && tags.isNotEmpty) {
        // 如果标签是字符串形式，尝试解析
        return tags.split(',').map((tag) => tag.trim()).where((tag) => tag.isNotEmpty).toList();
      }
    } catch (e) {
      print('DocumentTagsWidget: 解析标签失败: $e');
    }
    return [];
  }

  Widget _buildTagChips(BuildContext context, List<String> tags) {
    final displayTags = maxTags > 0 && tags.length > maxTags ? tags.take(maxTags).toList() : tags;
    final hasMoreTags = tags.length > maxTags && maxTags > 0;

    return Wrap(
      spacing: spacing,
      runSpacing: spacing,
      children: [
        ...displayTags.map((tag) => _buildTagChip(context, tag)),
        if (hasMoreTags && showMoreButton)
          _buildMoreTagsChip(context, tags.length - maxTags),
      ],
    );
  }

  Widget _buildTagChip(BuildContext context, String tag) {
    return Material(
      color: tagBackgroundColor,
      borderRadius: BorderRadius.circular(12),
      child: InkWell(
        borderRadius: BorderRadius.circular(12),
        onTap: () {
          onTagPressed?.call();
          _showTagDetails(context, tag);
        },
        onLongPress: () => _copyTagToClipboard(context, tag),
        child: Container(
          padding: EdgeInsets.symmetric(horizontal: 8, vertical: 4),
          child: Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              Icon(
                Icons.tag,
                size: fontSize,
                color: tagTextColor ?? Colors.blue[700],
              ),
              SizedBox(width: 4),
              Text(
                tag,
                style: TextStyle(
                  fontSize: fontSize,
                  color: tagTextColor ?? Colors.blue[700],
                  fontWeight: FontWeight.w500,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildMoreTagsChip(BuildContext context, int moreCount) {
    return Material(
      color: Colors.grey[200],
      borderRadius: BorderRadius.circular(12),
      child: InkWell(
        borderRadius: BorderRadius.circular(12),
        onTap: () => _showAllTags(context),
        child: Container(
          padding: EdgeInsets.symmetric(horizontal: 8, vertical: 4),
          child: Text(
            '+$moreCount',
            style: TextStyle(
              fontSize: fontSize,
              color: Colors.grey[700],
              fontWeight: FontWeight.w500,
            ),
          ),
        ),
      ),
    );
  }

  void _showTagDetails(BuildContext context, String tag) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Row(
          children: [
            Icon(Icons.tag, color: Colors.blue[700]),
            SizedBox(width: 8),
            Expanded(
              child: Text(
                tag,
                style: TextStyle(fontSize: 18),
              ),
            ),
          ],
        ),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('文档: ${document['title'] ?? '未知'}'),
            SizedBox(height: 8),
            Text(
              '这是从该文档中提取的知识标签，可以帮助您快速了解文档的主要内容和主题。',
              style: TextStyle(color: Colors.grey[600]),
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => _copyTagToClipboard(context, tag),
            child: Text('复制标签'),
          ),
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: Text('关闭'),
          ),
        ],
      ),
    );
  }

  void _showAllTags(BuildContext context) {
    final allTags = _getDocumentTags();
    
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text('所有标签'),
        content: Container(
          width: double.maxFinite,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Text(
                '文档: ${document['title'] ?? '未知'}',
                style: TextStyle(fontWeight: FontWeight.w500),
              ),
              SizedBox(height: 16),
              Flexible(
                child: SingleChildScrollView(
                  child: Wrap(
                    spacing: 8,
                    runSpacing: 8,
                    children: allTags.map((tag) => Chip(
                      label: Text(tag),
                      backgroundColor: tagBackgroundColor,
                      labelStyle: TextStyle(
                        color: tagTextColor ?? Colors.blue[700],
                      ),
                    )).toList(),
                  ),
                ),
              ),
            ],
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => _copyAllTags(context, allTags),
            child: Text('复制所有'),
          ),
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: Text('关闭'),
          ),
        ],
      ),
    );
  }

  void _copyTagToClipboard(BuildContext context, String tag) {
    Clipboard.setData(ClipboardData(text: tag));
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text('已复制标签: $tag'),
        duration: Duration(seconds: 2),
      ),
    );
  }

  void _copyAllTags(BuildContext context, List<String> tags) {
    final tagsText = tags.join(', ');
    Clipboard.setData(ClipboardData(text: tagsText));
    Navigator.of(context).pop();
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text('已复制所有标签'),
        duration: Duration(seconds: 2),
      ),
    );
  }
}

/// 简洁版文档标签显示组件（用于列表项）
class CompactDocumentTagsWidget extends StatelessWidget {
  final Map<String, dynamic> document;
  final int maxTags;
  final double fontSize;

  const CompactDocumentTagsWidget({
    Key? key,
    required this.document,
    this.maxTags = 2, // 在列表中只显示最重要的2个标签
    this.fontSize = 11.0,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return DocumentTagsWidget(
      document: document,
      showTitle: false,
      maxTags: maxTags,
      fontSize: fontSize,
      spacing: 3.0,
      padding: EdgeInsets.only(top: 4.0),
      tagBackgroundColor: Colors.grey[100]!,
      tagTextColor: Colors.grey[600],
    );
  }
} 